<template>
  <div class="g-select-handle">
    <a-button v-if="!hideHandle" type="text" class="select-handle icon-only-btn" @click="handlePrev">
      <i class="iconfont icon-arrow-left-s-line"></i>
    </a-button>
    <a-select
      v-model:value="value"
      class="w-256"
      :show-search="showSearch"
      :filter-option="filterOption"
      :placeholder="placeholder"
      :not-found-content="notFoundContent"
      :options="options"
      :field-names="fieldNames"
      allow-clear
      @search="handleSearch"
      @change="handleChange"
    />
    <a-button v-if="!hideHandle" type="text" class="select-handle icon-only-btn" @click="handleNext">
      <i class="iconfont icon-arrow-right-s-line"></i>
    </a-button>
  </div>
</template>

<script setup lang="ts">
  import type { SelectProps } from 'ant-design-vue'
  import { debounce } from 'g6-fn'
  import { ref } from 'vue'

  interface GSelectHandleProps extends SelectProps {
    hideHandle?: boolean
    getDataApi?: string
  }

  withDefaults(defineProps<GSelectHandleProps>(), {
    hideHandle: false,
    filterOption: false,
    notFoundContent: null,
    showSearch: true
  })

  const emits = defineEmits<{
    (e: 'change', value: string | string[] | number | number[]): void
  }>()

  const value = defineModel<string | string[] | number | number[]>('value')
  const currentIndex = ref<number>(-1)

  const options = ref<SelectProps['options']>([])

  const handlePrev = () => {
    if (!options.value) {
      return
    }
    if (options.value?.length === 0 || currentIndex.value <= 0) {
      return
    }

    currentIndex.value--
    value.value = options.value[currentIndex.value]?.value as string
    emits('change', value.value)
  }

  const handleNext = () => {
    if (!options.value) {
      return
    }
    if (options.value?.length === 0 || currentIndex.value >= options.value?.length - 1) {
      return
    }

    currentIndex.value++
    value.value = options.value[currentIndex.value]?.value as string
    emits('change', value.value)
  }

  const handleSearch = debounce((val: any) => {
    console.log(val, 'handleSearch')
    currentIndex.value = -1
    value.value = undefined
    if (!val) {
      options.value = []

      return
    }
    options.value = [
      { value: 'jack', label: 'Jack', index: 0 },
      { value: 'lucy', label: 'Lucy', index: 1 },
      { value: 'tom', label: 'Tom', index: 2 }
    ]
  }, 300)

  const handleChange = (val: any, option: any) => {
    val && (value.value = val as string)
    option && (currentIndex.value = option.index)
    emits('change', val)
  }
</script>

<style lang="less" scoped>
  .g-select-handle {
    display: flex;
    width: 100%;

    .select-handle {
      width: 36px;
      height: 36px;
    }
  }
</style>
